/**
 * @Project Name:blog-login-api
 * @Package Name:cn.hoofungson.blog.login.api.service.oauth2
 * @Since JDK 1.8
 */

package cn.hoofungson.blog.login.api.service.oauth2;

import cn.hoofungson.blog.login.api.client.oauth2.OAuth2FeignClient;
import cn.hoofungson.blog.login.api.domain.dto.oauth2.JwtCheckTransportDTO;
import cn.hoofungson.blog.login.api.domain.dto.oauth2.JwtTransportDTO;
import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

/**
 * @Description: OAuth2Service
 * @Author 胡松 hoofungson@163.com
 * @Date 2020-03-26 13:57
 * @Version V1.0
 */
@Service
public class OAuth2Service {

    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;

    /**
     * 认证
     *
     * @param username
     * @param password
     * @return
     **/
    public JwtTransportDTO auth(String username, String password) {
        ResponseEntity<JSONObject> responseEntity = this.oAuth2FeignClient
                .auth("password", "all", username, password);
        if (null == responseEntity || null == responseEntity.getBody()) {
            return null;
        }
        JSONObject jsonObject = responseEntity.getBody();
        JwtTransportDTO jwtTransportDTO = new JwtTransportDTO();
        jwtTransportDTO.setAccessToken(jsonObject.getStr("access_token"));
        jwtTransportDTO.setRefreshToken(jsonObject.getStr("refresh_token"));
        jwtTransportDTO.setTokenType(jsonObject.getStr("token_type"));
        jwtTransportDTO.setExpiresIn(jsonObject.getInt("expires_in"));
        jwtTransportDTO.setJti(jsonObject.getStr("jti"));
        jwtTransportDTO.setScope(jsonObject.getStr("scope"));
        return jwtTransportDTO;
    }

    /**
     * 检查Token
     *
     * @param token
     * @return
     **/
    public JwtCheckTransportDTO checkToken(String token) {
        ResponseEntity<JSONObject> responseEntity = this.oAuth2FeignClient.checkToken(token);
        if (null == responseEntity || null == responseEntity.getBody()) {
            return null;
        }
        JSONObject jsonObject = responseEntity.getBody();
        JwtCheckTransportDTO jwtCheckTransportDTO = new JwtCheckTransportDTO();
        jwtCheckTransportDTO.setUsername(jsonObject.getStr("user_name"));
        jwtCheckTransportDTO.setActive(jsonObject.getBool("active"));
        jwtCheckTransportDTO.setClientId(jsonObject.getStr("client_id"));
        jwtCheckTransportDTO.setJti(jsonObject.getStr("jti"));
        return jwtCheckTransportDTO;
    }
}
